package com.spark.sparktest


import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

/**
  * Created by zx on 2017/10/5.
  *
  */
object ScalaWord {
  val args1 = "/Users/hecj/workspace/xylink/spark/sparktest/test.txt"
  val args2 = "/Users/hecj/workspace/xylink/spark/sparktest/target/test"
  def main(args: Array[String]): Unit = {
    //创建spark配置，设置应用程序名字
    //val conf = new SparkConf().setAppName("ScalaWordCount")
    val conf = new SparkConf().setAppName("ScalaWordCount").setMaster("local[1]")
    //创建spark执行的入口
    val sc = new SparkContext(conf)
    //指定以后从哪里读取数据创建RDD（弹性分布式数据集）
    //sc.textFile(args(0)).flatMap(_.split(" ")).map((_, 1)).reduceByKey(_+_).sortBy(_._2, false).saveAsTextFile(args(1))

    val lines: RDD[String] = sc.textFile(args1)
    //切分压平
    val words: RDD[String] = lines.flatMap(_.split(" "))
   //  words.foreach(println)
    //将单词和一组合
    val wordAndOne: RDD[(String, Int)] = words.map((_, 1))
    
   // wordAndOne.foreach(println)
    
    
    //按key进行聚合
    val reduced:RDD[(String, Int)] = wordAndOne.reduceByKey(_+_)
    
   // reduced.foreach(println)
    
    //排序
    val sorted: RDD[(String, Int)] = reduced.sortBy(_._2, false)
    sorted.foreach(println)
    //将结果保存到HDFS中
//    sorted.saveAsTextFile(args2)
    //释放资源
    sc.stop()

  }

}